﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace MulticastTV
{
    class UdpRelayRequests
    {
        Socket socket = null;
        public volatile int chan = 0;
        public volatile bool set;
        public volatile string urip =Properties.Settings.Default.VlcIp;
        public volatile int urport = Properties.Settings.Default.VlcPort;

        public void setChannel()
        {
           if (urip.Length == 0)
               return;

            IPAddress ip = IPAddress.Parse(urip);
            IPEndPoint ipEnd = new IPEndPoint(ip, urport);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.ReceiveTimeout = 5000;
           
            try
            {
          
                socket.Connect(ipEnd);
            }
            catch { socket = null;  return; }

            try
            {
                Byte[] bytesSent;
                // Send
                 if (set)
                     bytesSent = Encoding.ASCII.GetBytes("GET /getchannel?" + chan.ToString("X") + "HTTP/1.1\r\n" + "Host: http://" + urip + ":" + urport.ToString() + "\r\n");
                 else
                     bytesSent = Encoding.ASCII.GetBytes("GET /getchannel?-1" + "HTTP/1.1\r\n" + "Host: http://" + urip + ":" + urport + "\r\n");
               
                 socket.Send(bytesSent);
            }
            catch
            {
                Dispose();
                return;
            }
            Dispose();
        }

        public void Dispose()
        {
            if (socket != null)
                socket.Close();
            socket = null;
        }
    }
}
